package com.xlyy.modbus.controller;

import com.alibaba.excel.EasyExcel;
import com.itextpdf.awt.AsianFontMapper;
import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.*;
import com.xlyy.modbus.bo.AvgDataBo;
import com.xlyy.modbus.entity.Categorize;
import com.xlyy.modbus.entity.MyData;
import com.xlyy.modbus.entity.MyTestresult;
import com.xlyy.modbus.property.Device;
import com.xlyy.modbus.service.IMyDataService;
import com.xlyy.modbus.service.IMyTestresultService;
import com.xlyy.modbus.vo.MyDataVO;
import jakarta.servlet.http.HttpServletResponse;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhoucanji
 * @since 2024-04-28
 */
@RestController
@RequestMapping("/myData")
public class MyDataController {
    @Value("${myproperty.modbus.differential}")
    private BigDecimal differential;

    @Autowired
    private IMyDataService myDataService;

    @Autowired
    private IMyTestresultService myTestresultService;

    @GetMapping("/list")
    public List<MyData> list(MyDataVO myDataVO){
        return  myDataService.list(myDataVO);
    }

    @PostMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response,@RequestBody MyDataVO myDataVO) throws Exception {
        List<MyData> myDataList=myDataService.list(myDataVO);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        EasyExcel.write(response.getOutputStream(),MyData.class).sheet("数据测量").doWrite(myDataList);
    }

    @PostMapping("/exportPdf")
    public void exportPdf(HttpServletResponse response,@RequestBody Categorize categorize) throws Exception {
        List<AvgDataBo> avgDataBoList=myDataService.avgDataBoList(categorize.getPch());
        System.out.println(avgDataBoList+"=--->avgDataBoListavgDataBoList");
        MyData startData = myDataService.startData(categorize.getPch());
        MyData endData = myDataService.endData(categorize.getPch());
        MyTestresult myTestresult = myTestresultService.getMyTestresult(categorize.getPch());
        if(myTestresult==null){
            myTestresult=new MyTestresult();
        }
        int num=Device.categorize.get(myTestresult.getCategorize()).size()-2;
        List<String> list=tableList(startData,endData,num);
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        for(AvgDataBo avgDataBo:avgDataBoList){
            if(num>=1){
                dataset.addValue(avgDataBo.getPv1(), "PV1", avgDataBo.getTime().split(" ")[1]);
            }
            if(num>=2){
                dataset.addValue(avgDataBo.getPv2(), "PV2", avgDataBo.getTime().split(" ")[1]);
            }
            if(num>=3){
                dataset.addValue(avgDataBo.getPv3(), "PV3", avgDataBo.getTime().split(" ")[1]);
            }
            if(num>=4){
                dataset.addValue(avgDataBo.getPv4(), "PV4", avgDataBo.getTime().split(" ")[1]);
            }
            if(num>=5){
                dataset.addValue(avgDataBo.getPv5(), "PV5", avgDataBo.getTime().split(" ")[1]);
            }
        }

        // 创建折线统计图
        JFreeChart chart = ChartFactory.createLineChart("测试曲线", "时间", "测试压力", dataset, PlotOrientation.VERTICAL, true, true, false);
        TextTitle textTitle=chart.getTitle();
        textTitle.setFont(new Font("宋体", Font.BOLD, 20));
        CategoryPlot plot = (CategoryPlot)chart.getPlot();
        CategoryAxis xAxis = plot.getDomainAxis();
        xAxis.setLabelFont(new Font("宋体", Font.BOLD, 16));// 设置X轴标签字体
        ValueAxis yAxis = plot.getRangeAxis();
        yAxis.setLabelFont(new Font("宋体", Font.BOLD, 16));// 设置y轴标签字体

        AsianFontMapper mapper=new AsianFontMapper("STSongStd-Light", "UniGB-UCS2-H");
        BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        com.itextpdf.text.Font keyfont1 = new com.itextpdf.text.Font (bfChinese, 20);
        com.itextpdf.text.Font keyfont2 = new com.itextpdf.text.Font (bfChinese, 18, Font.BOLD);
        com.itextpdf.text.Font keyfont3 = new com.itextpdf.text.Font (bfChinese, 16);

        // 生成PDF
        Document document = new Document();
        ByteArrayOutputStream fos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        document.open();

        Paragraph title20 = new Paragraph("宁波市泓欣液压有限公司", keyfont1);
        title20.setAlignment(1);
        title20.setSpacingAfter(5f);
        Paragraph title16 = new Paragraph(categorize.getName()+"试验在线检测记录", keyfont2);
        title16.setAlignment(1);
        title16.setSpacingAfter(20f);
        SimpleDateFormat dateFormat  = new SimpleDateFormat("HH:mm:ss");
        String startTime=dateFormat.format(startData.getCrateTime());
        long s=(endData.getCrateTime().getTime()-startData.getCrateTime().getTime())/1000;
        String sv=startData.getSv().toString();
        Paragraph note1= new Paragraph( "测试压力:"+sv +"Mpa  保压时间:"+s+" S", keyfont3);
        note1.setAlignment(1);
        note1.setSpacingAfter(5f);
        Paragraph note2= new Paragraph( "测试时间:"+startTime, keyfont3);
        note2.setAlignment(1);
        note2.setSpacingAfter(5f);
        Paragraph note3= new Paragraph( "壳体编号:"+myTestresult.getKtbh()+"  试验员:"+myTestresult.getSyy() +"  检验员:"+myTestresult.getJyy(), keyfont3);
        note3.setAlignment(1);
        note3.setSpacingAfter(10f);
        //创建一个表格对象
        float[] widths = { 60f, 80f, 80f,60f, 50f};
        PdfPTable pdfPTable = new PdfPTable(widths);
        PdfPCell pdfPCell = null;
        for (String str:list) {
            pdfPCell = new PdfPCell(new Paragraph(str,keyfont3));
            pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            pdfPTable.addCell(pdfPCell);
        }
        Paragraph c6= new Paragraph( "检测时间间隔:"+avgDataBoList.get(1).getC6(), keyfont3);
        c6.setSpacingAfter(5f);
        Paragraph d7= new Paragraph( "电磁阀通电次数:"+avgDataBoList.get(1).getD7(), keyfont3);
        d7.setSpacingAfter(5f);
        Paragraph note4= new Paragraph( "渗漏情况:"+myTestresult.getSlqi(), keyfont3);
        note4.setSpacingAfter(5f);
        Paragraph note5= new Paragraph( "宏观变形情况:"+myTestresult.getHgbxqk(), keyfont3);
        note5.setSpacingAfter(5f);
        Paragraph note6= new Paragraph( "异常情况:"+myTestresult.getYcqk(), keyfont3);
        note6.setSpacingAfter(5f);
        document.add(title20);
        document.add(title16);
        document.add(note1);
        document.add(note2);
        document.add(note3);
        document.add(pdfPTable);
        document.add(c6);
        document.add(d7);
        document.add(note4);
        document.add(note5);
        document.add(note6);
        PdfContentByte contentByte = writer.getDirectContent();
        PdfGraphics2D graphics2d = new PdfGraphics2D(contentByte, document.getPageSize().getWidth(), 300,mapper);
        Rectangle2D rectangle = new Rectangle2D.Double(0, 0,  document.getPageSize().getWidth(), 300);
        chart.draw(graphics2d, rectangle);
        graphics2d.dispose();
        document.close();
        response.setContentType("application/pdf");
        response.getOutputStream().write(fos.toByteArray()) ;
    }

    @GetMapping("/categorizeList")
    public List<Categorize> categorizeList(){
        return myDataService.categorizeList();
    }

    @GetMapping("/clearTable")
    public int  clearTable(){
        myTestresultService.clearTableTestresult();
        myDataService.clearTableData();
          return 1;
    }

    public String dp(BigDecimal startData, BigDecimal endData){
        BigDecimal v1=startData.compareTo(BigDecimal.ZERO) < 0? BigDecimal.ZERO:startData;
        BigDecimal v2=endData.compareTo(BigDecimal.ZERO) < 0? BigDecimal.ZERO:endData;
        return v1.subtract(v2).toString();

    }

    public String isZero(BigDecimal data){
        BigDecimal v=data.compareTo(BigDecimal.ZERO) < 0? BigDecimal.ZERO:data;
        return v.toString();
    }

    private String diff(BigDecimal startData, BigDecimal endData) {
        String result = "OK";
        String dp = dp(startData, endData);
        BigDecimal data = new BigDecimal(dp);

        if(differential.compareTo(data)<1){
            result = "NO";
        }
        return result;
    }

    public List<String> tableList(MyData startData,MyData endData,int num){
        List<String> list=new ArrayList<>();
        list.add("顺序号");
        list.add("起始压力(Mpa)");
        list.add("结束压力(Mpa)");
        list.add("压差(Mpa)");
        list.add("结果");
        if(num>=1){
            list.add("PV1");
            list.add(isZero(startData.getPv1()));
            list.add(isZero(endData.getPv1()));
            list.add(dp(startData.getPv1(),endData.getPv1()));
            list.add(diff(startData.getPv1(),endData.getPv1()));
        }
        if(num>=2){
            list.add("PV2");
            list.add(isZero(startData.getPv2()));
            list.add(isZero(endData.getPv2()));
            list.add(dp(startData.getPv2(),endData.getPv2()));
            list.add(diff(startData.getPv2(),endData.getPv2()));

        }
        if(num>=3){
            list.add("PV3");
            list.add(isZero(startData.getPv3()));
            list.add(isZero(endData.getPv3()));
            list.add(dp(startData.getPv3(),endData.getPv3()));
            list.add(diff(startData.getPv3(),endData.getPv3()));
        }
        if(num>=4){
            list.add("PV4");
            list.add(isZero(startData.getPv4()));
            list.add(isZero(endData.getPv4()));
            list.add(dp(startData.getPv4(),endData.getPv4()));
            list.add(diff(startData.getPv4(),endData.getPv4()));
        }
        if(num>=5){
            list.add("PV5");
            list.add(isZero(startData.getPv5()));
            list.add(isZero(endData.getPv5()));
            list.add(dp(startData.getPv5(),endData.getPv5()));
            list.add(diff(startData.getPv5(),endData.getPv5()));
        }
        return list;
    }




}
